package v1

import (
	"DuckShop/pkg/com"
	"DuckShop/pkg/common"
	pkg "DuckShop/pkg/jwt"
	"DuckShop/pkg/middlewares"
	"fmt"
	"github.com/gin-gonic/gin"
)

type UserController interface {
	CreateUserController()
	ListUserController()
	UserEnterController()
	UserProfileController()
}
type UserControllerImpl struct {
	userAPI UserAPI
}

func (uc *UserControllerImpl) CreateUserController(c *gin.Context) {
	var p CreateUserParams
	err := c.ShouldBindJSON(&p)
	if err != nil {
		common.ErrorValidator(c, err)
		return
	}
	err = uc.userAPI.CreateUser(&p)
	if err != nil {
		com.ResponseData(c, com.CodeFailed, err.Error())
		return
	}
	com.ResponsePureSuccess(c)
}
func (uc *UserControllerImpl) ListUserController(c *gin.Context) {
	var p GetUserListParams
	err := c.ShouldBindJSON(&p)
	if err != nil {
		common.ErrorValidator(c, err)
		return
	}
	list, err := uc.userAPI.GetUserList(&p)
	if err != nil {
		com.ResponseData(c, com.CodeFailed, err.Error())
		return
	}
	com.ResponseData(c, com.CodeSuccess, list)
}
func (uc *UserControllerImpl) UserEnterController(c *gin.Context) {
	// TODO 介入验证码
	var p UserEnterParams
	err := c.ShouldBindJSON(&p)
	if err != nil {
		common.ErrorValidator(c, err)
		return
	}
	ok, userid, err := uc.userAPI.ValidatorEnterUser(&p)
	fmt.Println(ok)
	if err != nil {
		com.ResponseData(c, com.CodeFailed, err.Error())
		return
	}
	token, err := pkg.GenToken(p.Username, userid)
	if err != nil {
		com.ResponseData(c, com.CodeFailed, err.Error())
		return
	}
	com.ResponseData(c, com.CodeSuccess, token)
}
func (uc *UserControllerImpl) UserProfileController(c *gin.Context) {
	value, exists := c.Get(middlewares.CtxUserId)
	if exists {
		u, err := uc.userAPI.GetUserByID(value.(string))
		if err != nil {
			com.ResponseData(c, com.CodeFailed, err.Error())
			return
		} else {
			com.ResponseData(c, com.CodeSuccess, u)
			return
		}
	} else {
		com.ResponseNoAuth(c)
	}
}
